package com.herr.springboot.data.mybatismulti.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.mapper.autoconfigure.SpringBootVFS;

import jakarta.annotation.Resource;
import javax.sql.DataSource;

/**
 * Primary数据源配置
 * 本质走的都是sqlSessionTemplate，因此sqlSessionTemplateRef和sqlSessionFactoryRef配置一个就好
 */
@Configuration
@MapperScan(basePackages = MyBatisConfigPrimary.PACKAGE,sqlSessionFactoryRef = "primarySqlSessionFactory")
public class MyBatisConfigPrimary {
    // 数据源mapper隔离
    static final String PACKAGE = "com.herr.springboot.data.mybatismulti.mapper.primary";
    static final String MAPPER_LOCATION = "classpath:mapping/primary/*Mapper.xml";
    static final String MODEL_PACKAGE ="com.herr.springboot.data.mybatismulti.model";

    @Resource(name = "dsPrimary")
    DataSource dsPrimary;

    @Bean(name = "primarySqlSessionFactory")
    @Primary
    SqlSessionFactory primarySqlSessionFactory() {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        try {
            bean.setDataSource(dsPrimary);
            bean.setMapperLocations(new PathMatchingResourcePatternResolver().
                    getResources(MyBatisConfigPrimary.MAPPER_LOCATION));
            bean.setTypeAliasesPackage(MyBatisConfigPrimary.MODEL_PACKAGE); //必须放在configuration语句前
            bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true); //设置驼峰
            //bean.setVfs(SpringBootVFS.class);//设置SpringBootVFS
            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Bean
    SqlSessionTemplate primarySqlSessionTemplate() {
        return new SqlSessionTemplate(primarySqlSessionFactory());
    }

    @Bean(name = "primaryTransactionManager")
    public DataSourceTransactionManager primaryTransactionManager() {
        return new DataSourceTransactionManager(dsPrimary);
    }
}
